import subprocess
import pysvn
import os
import shutil

update_file_list = set()
case_result_file = None

def Operator(service, *args, **kwargs):
    if service == 'process':
        return StartProcess(*args, **kwargs)
    elif service == 'svn':
        return SvnService(*args, **kwargs)
    elif service == 'filesystem':
        return FileSystemService(*args, **kwargs)
    elif service == 'uploadcaseresult':
        return UpdateCaseFile(*args, **kwargs)
    else:
        raise ValueError('not support operator')

def StartProcess(args, executable = None, env = None, cwd = None):
    p = subprocess.Popen(args = args, executable = executable, env = env, cwd = cwd)
    p.wait()
    return True

def StartCaseProcess(args, caseparamname, executable = None, env = None, cwd = None):
    args = args + "  " + caseparamname + "=" + sysargsparse.args.case_param
    p = subprocess.Popen(args = args, executable = executable, env = env, cwd = cwd)
    p.wait()
    return True

def GetLogin(realm, user, may_save):
        return True, 'zhoucheng', 'bbc1981', False
    
def SvnService(svntype, *args, **kwargs):
    svn = pysvn.Client()
    svn.callback_get_login = GetLogin
    if svntype == 'update':
        svn.update(*args, **kwargs)
    elif svntype == 'checkout':
        svn.checkout(*args, **kwargs)
    return True
    
def FileSystemService(fstype, *args, **kwargs):
    if fstype == 'create':
        os.makedirs(*args, **kwargs)
    elif fstype == 'copy':
        shutil.copy(*args, **kwargs)
    elif fstype == 'rename':
        os.rename(*args, **kwargs)
    elif fstype == 'move':
        shutil.move(*args, **kwargs)
    else:
        raise ValueError('not support file system operator')
    return True

def UpdateCaseFile(path):
    if not os.path.isfile(path):
        raise ValueError('%s file not exits' % path)
    global case_result_file
    case_result_file = path
    return True
